"""
Simple usage examples for the Python Backend Toolkit.
These examples demonstrate basic usage of each module.
"""

import asyncio
from datetime import datetime

# Example 1: Database Operations
async def database_example():
    """Example of database operations."""
    print("=== Database Example ===")
    
    from python_backend_toolkit.database import DatabaseSession, DatabaseConfig, BaseRepository
    from python_backend_toolkit.database.base import BaseModel
    from sqlalchemy import Column, String
    
    # Define a simple model
    class User(BaseModel):
        name = Column(String(100), nullable=False)
        email = Column(String(255), unique=True, nullable=False)
    
    # Setup database
    db_config = DatabaseConfig(database_url="sqlite:///./example.db")
    db_session = DatabaseSession(db_config)
    db_session.create_tables()
    
    # Use repository
    with db_session.session_scope() as db:
        user_repo = BaseRepository(User, db)
        
        # Create user
        user_data = {"name": "John Doe", "email": "john@example.com"}
        user = user_repo.create(user_data)
        print(f"Created user: {user.name} ({user.email})")
        
        # Find user
        found_user = user_repo.get_by_id(user.id)
        print(f"Found user: {found_user.name}")


# Example 2: Caching
async def cache_example():
    """Example of caching operations."""
    print("\n=== Cache Example ===")
    
    from python_backend_toolkit.cache import MemoryCache, cached
    
    # Setup cache
    cache = MemoryCache()
    
    # Basic cache operations
    await cache.set("key1", "value1", ttl=60)
    value = await cache.get("key1")
    print(f"Cached value: {value}")
    
    # Using cache decorator
    @cached(expire=30, key_func=lambda x: f"calc:{x}")
    async def expensive_calculation(number: int) -> int:
        print(f"Calculating for {number}...")
        await asyncio.sleep(0.1)  # Simulate work
        return number * number
    
    # First call - will calculate
    result1 = await expensive_calculation(5)
    print(f"First call result: {result1}")
    
    # Second call - will use cache
    result2 = await expensive_calculation(5)
    print(f"Second call result: {result2}")


# Example 3: HTTP Client
async def http_client_example():
    """Example of HTTP client usage."""
    print("\n=== HTTP Client Example ===")
    
    from python_backend_toolkit.http_client import AsyncHTTPClient
    
    async with AsyncHTTPClient() as client:
        try:
            # Make a GET request
            response = await client.get("https://httpbin.org/json")
            print(f"Status: {response.status_code}")
            print(f"Response: {response.json}")
        except Exception as e:
            print(f"Request failed: {e}")


# Example 4: Validation
async def validation_example():
    """Example of validation."""
    print("\n=== Validation Example ===")
    
    from python_backend_toolkit.utils import EmailValidator, PasswordValidator
    
    # Email validation
    email_validator = EmailValidator()
    emails = ["valid@example.com", "invalid-email", "test@test.co.uk"]
    
    for email in emails:
        result = email_validator.validate(email)
        print(f"Email '{email}': {'Valid' if result.is_valid else 'Invalid'}")
        if not result.is_valid:
            print(f"  Errors: {result.errors}")
    
    # Password validation
    password_validator = PasswordValidator()
    passwords = ["weak", "StrongPass123!", "short"]
    
    for password in passwords:
        result = password_validator.validate(password)
        print(f"Password '{password}': {'Valid' if result.is_valid else 'Invalid'}")
        if not result.is_valid:
            print(f"  Errors: {result.errors}")


# Example 5: Utilities
async def utilities_example():
    """Example of utility functions."""
    print("\n=== Utilities Example ===")
    
    from python_backend_toolkit.utils import (
        generate_uuid, generate_slug, format_datetime,
        retry, rate_limit, Paginator
    )
    
    # Generate UUID and slug
    uuid = generate_uuid()
    slug = generate_slug("This is a Sample Title!")
    print(f"UUID: {uuid}")
    print(f"Slug: {slug}")
    
    # Format datetime
    now = datetime.now()
    formatted = format_datetime(now)
    print(f"Formatted datetime: {formatted}")
    
    # Retry decorator
    @retry(max_attempts=3, delay=0.1)
    async def sometimes_fails():
        import random
        if random.random() < 0.7:  # 70% chance of failure
            raise Exception("Random failure")
        return "Success!"
    
    try:
        result = await sometimes_fails()
        print(f"Retry example: {result}")
    except Exception as e:
        print(f"Retry example failed: {e}")
    
    # Pagination
    paginator = Paginator()
    items = list(range(1, 51))  # 50 items
    
    page_result = paginator.paginate_list(items, page=2, size=10)
    print(f"Page 2 items: {page_result.items}")
    print(f"Total: {page_result.total}, Has next: {page_result.has_next}")


# Example 6: Logging
async def logging_example():
    """Example of logging."""
    print("\n=== Logging Example ===")
    
    from python_backend_toolkit.logging import get_logger
    
    logger = get_logger("ExampleApp")
    
    # Different log levels
    logger.info("Application started", version="1.0.0")
    logger.warning("This is a warning", user_id=123)
    logger.error("An error occurred", error_code="ERR_001")
    
    # Structured logging
    logger.info(
        "User action",
        user_id=123,
        action="login",
        ip_address="192.168.1.1",
        timestamp=datetime.now().isoformat()
    )


# Example 7: Authentication
async def auth_example():
    """Example of authentication."""
    print("\n=== Authentication Example ===")
    
    from python_backend_toolkit.auth import JWTHandler, PasswordHandler
    
    # Password handling
    password_handler = PasswordHandler()
    
    password = "my_secure_password"
    hashed = password_handler.hash_password(password)
    print(f"Hashed password: {hashed[:50]}...")
    
    is_valid = password_handler.verify_password(password, hashed)
    print(f"Password verification: {is_valid}")
    
    # JWT handling
    jwt_handler = JWTHandler()
    
    payload = {"sub": "user123", "role": "user"}
    token = jwt_handler.create_access_token(payload)
    print(f"JWT Token: {token[:50]}...")
    
    decoded = jwt_handler.decode_token(token)
    print(f"Decoded payload: {decoded}")


# Example 8: API Response
async def api_response_example():
    """Example of API responses."""
    print("\n=== API Response Example ===")
    
    from python_backend_toolkit.api import SuccessResponse, ErrorResponse, ListResponse
    
    # Success response
    success = SuccessResponse.create(
        data={"id": 1, "name": "John Doe"},
        message="User retrieved successfully"
    )
    print(f"Success response: {success.dict()}")
    
    # List response
    items = [{"id": 1, "name": "Item 1"}, {"id": 2, "name": "Item 2"}]
    list_response = ListResponse.create(
        items=items,
        message="Items retrieved successfully"
    )
    print(f"List response count: {len(list_response.data)}")
    
    # Error response
    error = ErrorResponse.create(
        message="Validation failed",
        error_code="VALIDATION_ERROR",
        details={"field": "email", "issue": "invalid format"}
    )
    print(f"Error response: {error.dict()}")


# Main function to run all examples
async def main():
    """Run all examples."""
    print("Python Backend Toolkit - Simple Examples\n")
    
    examples = [
        database_example,
        cache_example,
        http_client_example,
        validation_example,
        utilities_example,
        logging_example,
        auth_example,
        api_response_example,
    ]
    
    for example in examples:
        try:
            await example()
        except Exception as e:
            print(f"Example failed: {e}")
    
    print("\n=== All examples completed ===")


if __name__ == "__main__":
    asyncio.run(main())